// effect_sparks

local effect_sparks = Assault.Entities:New("effect_sparks")

// Derive from entity

effect_sparks:DeriveFromEntity("effect_base")

// On entity created

function effect_sparks:OnEntitySpawn()
	local Table = {}
	
	// Size, width and position
	
	local Position = self:EntityGetPosition()
	local Width = self:EntityGetVariable("Width") or 2
	
	// Loop
	
	for I = 1, 6 do
		Table[I] = {}
		
		// Variables
		
		Table[I].X        = Position.X
		Table[I].Y        = Position.Y
		Table[I].W        = Width
		Table[I].H        = math.random(2, 8)
		Table[I].Speed    = math.random(2, 8)
		Table[I].Rotation = math.random(0, 360)
	end
	
	// Sparks variable
	
	self:EntitySetVariable("Sparks", Table)
end

// On entity paint

function effect_sparks:OnEntityPaint()
	local Sparks = self:EntityGetVariable("Sparks")
	
	// Material and color
	
	local Material = self:EntityGetMaterial()
	local Color = self:EntityGetColor()
	
	// Texture ID
	
	Material = surface.GetTextureID(Material)
	
	// Set texture and draw color
	
	surface.SetTexture(Material)
	surface.SetDrawColor(Color.r, Color.g, Color.b, Color.a)
	
	// Loop
	
	for K, V in pairs(Sparks) do
		// Sin and Cos
		
		local Sin = math.sin(math.rad(V.Rotation)) * V.Speed
		local Cos = math.cos(math.rad(V.Rotation)) * V.Speed
		
		// Set new X and Y positions
		
		Sparks[K].X = V.X - Sin
		Sparks[K].Y = V.Y - Cos
		
		// Set texture and draw color then draw the textured rect rotated
		
		surface.DrawTexturedRectRotated(Sparks[K].X + (V.W / 2), Sparks[K].Y + (V.H / 2), V.W, V.H, V.Rotation)
	end
end

// On entity think

function effect_sparks:OnEntityThink()
	local Sparks = self:EntityGetVariable("Sparks")
	
	// Loop
	
	for K, V in pairs(Sparks) do
		// Reduce speed
		
		Sparks[K].Speed = math.Clamp(Sparks[K].Speed - 0.25, 0, Sparks[K].Speed)
		
		// Reduce H
		
		Sparks[K].H = math.Clamp(Sparks[K].H - 0.25, 0, Sparks[K].H)
		
		// Check H
		
		if (Sparks[K].H == 0) then Sparks[K] = nil end
	end
	
	// Check amount of sparks
	
	if (#Sparks == 0) then self:EntityRemove() end
end

// Create

effect_sparks:Create()